package com.ruoyi.system.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.GuangDianUser;
import com.ruoyi.system.service.IGuangDianUserService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 广电用户Controller
 * 
 * @author ruoyi
 * @date 2024-01-18
 */
@Controller
@RequestMapping("/system/guangdian")
public class GuangDianUserController extends BaseController
{
    private String prefix = "system/guangdian";

    @Autowired
    private IGuangDianUserService guangDianUserService;

    @RequiresPermissions("system:guangdian:view")
    @GetMapping()
    public String guangdian()
    {
        return prefix + "/guangdian";
    }

    /**
     * 查询广电用户列表
     */
    @RequiresPermissions("system:guangdian:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(GuangDianUser guangDianUser)
    {
        startPage();
        List<GuangDianUser> list = guangDianUserService.selectGuangDianUserList(guangDianUser);
        return getDataTable(list);
    }

    /**
     * 导出广电用户列表
     */
    @RequiresPermissions("system:guangdian:export")
    @Log(title = "广电用户", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(GuangDianUser guangDianUser)
    {
        List<GuangDianUser> list = guangDianUserService.selectGuangDianUserList(guangDianUser);
        ExcelUtil<GuangDianUser> util = new ExcelUtil<GuangDianUser>(GuangDianUser.class);
        return util.exportExcel(list, "广电用户数据");
    }

    /**
     * 新增广电用户
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存广电用户
     */
    @RequiresPermissions("system:guangdian:add")
    @Log(title = "广电用户", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(GuangDianUser guangDianUser)
    {
        return toAjax(guangDianUserService.insertGuangDianUser(guangDianUser));
    }

    /**
     * 修改广电用户
     */
    @RequiresPermissions("system:guangdian:edit")
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap)
    {
        GuangDianUser guangDianUser = guangDianUserService.selectGuangDianUserById(id);
        mmap.put("guangDianUser", guangDianUser);
        return prefix + "/edit";
    }

    /**
     * 修改保存广电用户
     */
    @RequiresPermissions("system:guangdian:edit")
    @Log(title = "广电用户", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(GuangDianUser guangDianUser)
    {
        return toAjax(guangDianUserService.updateGuangDianUser(guangDianUser));
    }

    /**
     * 删除广电用户
     */
    @RequiresPermissions("system:guangdian:remove")
    @Log(title = "广电用户", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(guangDianUserService.deleteGuangDianUserByIds(convertStrArrayToLongArray(ids.split(","))));
    }

    /**
     * 查看广电用户详情
     */
    @RequiresPermissions("system:guangdian:view")
    @GetMapping("/detail/{id}")
    public String detail(@PathVariable("id") Long id, ModelMap mmap)
    {
        GuangDianUser guangDianUser = guangDianUserService.selectGuangDianUserById(id);
        mmap.put("guangDianUser", guangDianUser);
        return prefix + "/detail";
    }

    /**
     * 统计标签用户数量
     */
    @RequiresPermissions("system:guangdian:view")
    @PostMapping("/countByTag")
    @ResponseBody
    public AjaxResult countByTag(String tagField, String tagValue)
    {
        int count = guangDianUserService.countUserByTag(tagField, tagValue);
        return AjaxResult.success().put("count", count);
    }

    /**
     * 获取仪表盘数据页面
     */
    @RequiresPermissions("system:guangdian:dashboard")
    @GetMapping("/dashboard")
    public String dashboard(ModelMap mmap)
    {
        return prefix + "/dashboard";
    }
    
    /**
     * 获取仪表盘数据接口
     */
    @PreAuthorize("@ss.hasPermi('system:guangDian:dashboard')")
    @GetMapping("/dashboardData")
    @ResponseBody
    public AjaxResult getDashboardData()
    {
        try {
            Map<String, Object> dashboardData = new HashMap<>();
            
            // 统计总用户数
            GuangDianUser query = new GuangDianUser();
            int totalUsers = guangDianUserService.countGuangDianUser(query);
            dashboardData.put("totalUsers", totalUsers);
            
            // 统计重度用户数
            int heavyUsers = guangDianUserService.countUserByTag("is_heavy_user", "是");
            dashboardData.put("heavyUsers", heavyUsers);
            
            // 统计忠诚用户数
            int loyalUsers = guangDianUserService.countUserByTag("is_loyal_user", "是");
            dashboardData.put("loyalUsers", loyalUsers);
            
            // 统计宽带用户数
            int broadbandUsers = guangDianUserService.countUserByTag("broadbandPenetration", "是");
            dashboardData.put("broadbandUsers", broadbandUsers);
            
            // 统计电视消费水平分布
            int highTvConsumption = guangDianUserService.countUserByTag("tvConsumptionLevel", "高");
            int mediumTvConsumption = guangDianUserService.countUserByTag("tvConsumptionLevel", "中");
            int lowTvConsumption = guangDianUserService.countUserByTag("tvConsumptionLevel", "低");
            
            dashboardData.put("highTvConsumption", highTvConsumption);
            dashboardData.put("mediumTvConsumption", mediumTvConsumption);
            dashboardData.put("lowTvConsumption", lowTvConsumption);
            
            // 用户标签分布 - 用于饼图展示
            dashboardData.put("tagDistribution", new HashMap<String, Long>() {
                { 
                    put("heavyUser", (long)heavyUsers);
                    put("loyalUser", (long)loyalUsers);
                    put("broadbandUser", (long)broadbandUsers);
                    put("regularUser", (long)(totalUsers - heavyUsers - loyalUsers - broadbandUsers));
                }
            });
            
            // 服务品牌分布统计
            try {
                long cableTvCount = guangDianUserService.countUserByTag("smName", "有线电视");
                long iptvCount = guangDianUserService.countUserByTag("smName", "IPTV");
                dashboardData.put("brandDistribution", new HashMap<String, Long>() {
                    { 
                        put("cableTv", cableTvCount);
                        put("iptv", iptvCount);
                        put("ott", (long)guangDianUserService.countUserByTag("smName", "OTT"));
                        put("others", (long)(totalUsers - cableTvCount - iptvCount - guangDianUserService.countUserByTag("smName", "OTT")));
                    }
                });
            } catch (Exception e) {
                // 如果字段不存在，使用默认值
                dashboardData.put("brandDistribution", new HashMap<String, Long>() {
                    { 
                        put("cableTv", (long)(totalUsers * 70 / 100));
                        put("iptv", (long)(totalUsers * 25 / 100));
                        put("ott", (long)(totalUsers * 3 / 100));
                        put("others", (long)(totalUsers * 2 / 100));
                    }
                });
            }
            
            // 渗透率分析数据
            dashboardData.put("penetrationRates", new HashMap<String, Double>() {
                { 
                    put("broadband", totalUsers > 0 ? (double) Math.round(broadbandUsers * 10000.0 / totalUsers) / 100 : 0);
                    put("heavyUser", totalUsers > 0 ? (double) Math.round(heavyUsers * 10000.0 / totalUsers) / 100 : 0);
                    put("loyalUser", totalUsers > 0 ? (double) Math.round(loyalUsers * 10000.0 / totalUsers) / 100 : 0);
                }
            });
            
            // 添加数据更新时间
            dashboardData.put("updateTime", new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
            
            return AjaxResult.success(dashboardData);
        } catch (Exception e) {
            logger.error("获取仪表盘数据失败", e);
            return AjaxResult.error("获取仪表盘数据失败：" + e.getMessage());
        }
    }
    }

    /**
     * 获取仪表盘统计数据（旧接口，保留兼容性）
     */
    @RequiresPermissions("system:guangdian:dashboard")
    @PostMapping("/dashboard/data")
    @ResponseBody
    public AjaxResult getDashboardDataLegacy()
    {
        return getDashboardData();
    }

    /**
     * 手动导入CSV数据
     */
    @RequiresPermissions("system:guangdian:import")
    @Log(title = "广电用户", businessType = BusinessType.IMPORT)
    @PostMapping("/importCsv")
    @ResponseBody
    public AjaxResult importCsv(String filePath, Integer limit)
    {
        if (limit == null || limit <= 0) {
            limit = 100;
        }
        int importedCount = guangDianUserService.importGuangDianUserFromCsv(filePath, limit);
        return AjaxResult.success("成功导入 " + importedCount + " 条数据");
    }

    /**
     * 获取仪表盘数据（优化版，提供完整的多维度统计数据）
     */
    @PreAuthorize("@ss.hasPermi('system:guangDian:dashboard')")
    @GetMapping("/dashboardData")
    public AjaxResult getDashboardData()
    {
        try {
            // 构建响应数据
            Map<String, Object> dashboardData = new HashMap<>();
            
            // 基础用户统计
            long totalUsers = guangDianUserService.count();
            long heavyUsers = guangDianUserService.countByTag("isHeavyUser", "是");
            long loyalUsers = guangDianUserService.countByTag("isLoyalUser", "是");
            long broadbandUsers = guangDianUserService.countByTag("isBroadbandUser", "是");
            
            dashboardData.put("totalUsers", totalUsers);
            dashboardData.put("heavyUsers", heavyUsers);
            dashboardData.put("loyalUsers", loyalUsers);
            dashboardData.put("broadbandUsers", broadbandUsers);
            
            // 电视消费水平分布
            long highTvConsumption = guangDianUserService.countByTag("tvConsumptionLevel", "高");
            long mediumTvConsumption = guangDianUserService.countByTag("tvConsumptionLevel", "中");
            long lowTvConsumption = guangDianUserService.countByTag("tvConsumptionLevel", "低");
            
            dashboardData.put("highTvConsumption", highTvConsumption);
            dashboardData.put("mediumTvConsumption", mediumTvConsumption);

    }
    
    /**
     * 手动导入CSV数据
     */
    @PreAuthorize("@ss.hasPermi('system:guangDian:import')")
    @PostMapping("/importCsv")
    @ResponseBody
    public AjaxResult importCsvData(@RequestParam String filePath, @RequestParam(required = false, defaultValue = "0") Integer limit)
    {
        try {
            int importedCount = guangDianUserService.importFromCsv(filePath, limit);
            return AjaxResult.success("CSV数据导入成功，共导入" + importedCount + "条记录");
        } catch (Exception e) {
            logger.error("CSV数据导入失败", e);
            return AjaxResult.error("CSV数据导入失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取最近的用户数据
     */
    @PreAuthorize("@ss.hasPermi('system:guangDian:dashboard')")
    @GetMapping("/recentUsers")
    @ResponseBody
    public AjaxResult getRecentUsers(@RequestParam(defaultValue = "10") Integer limit)
    {
        try {
            List<GuangDianUser> recentUsers = guangDianUserService.findRecentData(limit);
            return AjaxResult.success(recentUsers);
        } catch (Exception e) {
            return AjaxResult.error("获取最近用户数据失败：" + e.getMessage());
        }
    }
}